package com.atguigu.spzx.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.manager.mapper.SysRoleUserMapper;
import com.atguigu.spzx.manager.mapper.SysUserMapper;
import com.atguigu.spzx.manager.service.SysUserService;
import com.atguigu.spzx.model.dto.system.AssignRoleDto;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.dto.system.SysUserDto;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.system.LoginVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 作者:hfj
 * 功能:
 * 日期: 2024/3/21 21:06
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //用户登录
    @Override
    public LoginVo login(LoginDto loginDto) {

        //获取输入的验证码和存储到redis的key名称 loginDto获得到
        String captcha = loginDto.getCaptcha();
        String key = loginDto.getCodeKey();

        //获取redis的key,查询redis里面存储验证码
        String redisCode = redisTemplate.opsForValue().get("user:validate" + key);

        //比较输入的验证码是否为空或者是否不一致
        if(StrUtil.isEmpty(redisCode) || !StrUtil.equalsAnyIgnoreCase(redisCode,captcha)){
            throw new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        //一致把redis的验证码删除
        redisTemplate.delete("user:validate" + key);


        //1.获取提交的用户名,loginDto获取到名字
        String userName = loginDto.getUserName();

        //2.根据用户名查询数据库表sys_user表 方法写到SysUserMapper.xml文件里
        SysUser sysUser = sysUserMapper.selectUserInfoByUserName(userName);

        //3.根据用户名查询数据库信息,用户不存在返回错误信息
        if(sysUser == null){
            //throw new RuntimeException("用户名不存在");
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }

        //4.用户名存在去获取密码,并比较是否和数据库的密码是否一致
        String database_password = sysUser.getPassword();

        //5.把输入的密码进行加密,在比较数据库的密码,MD5
        String input_password = DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());

        //6.比较
        if (!input_password.equals(database_password)){
            //throw new RuntimeException("密码不正确");
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }

        //7.比较成功生成一个token当作用户的唯一标识
        String token = UUID.randomUUID().toString().replaceAll("-","");

        //8.把登录成功的信息存放在redis里面
        //key:token value:用户信息
        redisTemplate.opsForValue().set("user:login" + token, JSON.toJSONString(sysUser),7, TimeUnit.DAYS);

        //9.返回loginVo对象
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);

        return loginVo;
    }

    //获取当前登录用户信息
    @Override
    public SysUser getUserInfo(String token) {
        String userJson = redisTemplate.opsForValue().get("user:login" + token);
        SysUser sysUser = JSON.parseObject(userJson, SysUser.class);
        return sysUser;
    }

    //用户退出
    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login" + token);
    }

    //用户条件分页查询接口
    @Override
    public PageInfo<SysUser> findByPage(Integer pageNum, Integer pageSize, SysUserDto sysUserDto) {
        PageHelper.startPage(pageNum,pageSize);
        List<SysUser> list = sysUserMapper.findByPage(sysUserDto);
        PageInfo<SysUser> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    //用户添加
    @Override
    public void saveSysUser(SysUser sysUser) {
        //1.判断用户名不能重复
        String userName = sysUser.getUserName();
        SysUser dbSysUser = sysUserMapper.selectUserInfoByUserName(userName);
        if (dbSysUser != null){
            //抛出用户名存在异常
            throw new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }

        //2.用户密码加密处理
        String md5_password = DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes());
        sysUser.setPassword(md5_password);

        //3.设置status的值 1代表可用 0代表不可用
        sysUser.setStatus(1);

        sysUserMapper.save(sysUser);
    }

    //用户修改
    @Override
    public void updateSysUser(SysUser sysUser) {
        //1.判断用户名不能重复
        String userName = sysUser.getUserName();
        SysUser dbSysUser = sysUserMapper.selectUserInfoByUserName(userName);
        if (dbSysUser != null){
            //抛出用户名存在异常
            throw new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }

        sysUserMapper.update(sysUser);
    }

    //根据用户Id删除用户(逻辑删除)
    @Override
    public void deleteById(Long userId) {
        sysUserMapper.delete(userId);
    }

    //用户分配角色
    @Override
    public void doAssign(AssignRoleDto assignRoleDto) {
        //1.根据userId删除之前分配的角色数据
        sysRoleUserMapper.deleteByUserId(assignRoleDto.getUserId());

        //2，重新分配角色数据
        List<Long> roleIdList = assignRoleDto.getRoleIdList();
        //遍历得到每个角色Id
        for (Long roleId: roleIdList){
            sysRoleUserMapper.doAssign(assignRoleDto.getUserId(),roleId);
        }
    }

}
